
import os
import shutil
from datetime import datetime
import fire
import zipfile

ENV_CONFIG = {
    "default": ["hello_world.py"],
}


def build_html():
    print("编译GUI页面")
    path = os.path.join(os.getcwd(), "gui", "rpa-bot")
    print(path)
    os.system(f"cd {path} && yarn build")


def build_exe(path):
    import PyInstaller.building.templates 
    import PyInstaller.__main__

    PyInstaller.building.templates.splashtmpl = """splash = Splash(%(splash_image)r,
                binaries=a.binaries,
                datas=a.datas,
                text_pos=(20,20),
                text_size=12,
                minify_script=True)
    """

    PyInstaller.__main__.run(
        ['window.py', '--onefile',  '-w',
            "--splash=build-assets/splash.png",
            "--key=emUTKsvYRaoE4bcd", 
            "--icon=build-assets/icon.ico",
            "--hidden-import=pynput.keyboard._win32" ,
            "--hidden-import=pynput.mouse._win32" 
         ])
    shutil.copy(os.path.join(os.getcwd(), "dist", "window.exe"), os.path.join(path, "RPA.exe"))
    


def create_dist_dir(env):
    v = datetime.now().strftime(f"%Y%m%d%H%M%S")
    print(f'打包新版本: {env}, {v}')
    path = os.path.join(os.getcwd(), "dist", env, v)
    if not os.path.exists(path):
        os.makedirs(path)
    return path

def copy_tools(dest):
    print("复制工具程序")
    shutil.copy(os.path.join(os.getcwd(), "chromedriver.exe"), os.path.join(dest, 'chromedriver.exe'))
    shutil.copy(os.path.join(os.getcwd(), "IEDriverServer.exe"), os.path.join(dest, 'IEDriverServer.exe'))
    # shutil.copy(os.path.join(os.getcwd(), "build-assets", "run.bat"), os.path.join(dest, 'run.bat'))

def copy_html(dest):
    print("复制GUI页面")
    shutil.copytree(os.path.join(os.getcwd(), "gui", "rpa-bot", "dist", "static"),
                    os.path.join(dest, "static", "static"))
    shutil.copy(os.path.join(os.getcwd(), "gui", "rpa-bot", "dist", "index.html"),
                os.path.join(dest, "static", "index.html"))
    shutil.copy(os.path.join(os.getcwd(), "gui", "rpa-bot", "dist", "favicon.ico"),
                os.path.join(dest, "static", "favicon.ico"))

def copy_scripts(env, dest):
    print("复制RPA脚本")
    scripts = ENV_CONFIG.get(env)
    path = os.path.join(dest, "scripts")
    if not os.path.exists(path):
        os.makedirs(path)
    for script in scripts:
        shutil.copy(os.path.join(os.getcwd(), "scripts", script), os.path.join(path, script))

def build(env):
    path = create_dist_dir(env)
    build_exe(path)
    copy_tools(path)
    build_html()
    copy_html(path)
    copy_scripts(env, path)

if __name__ == '__main__':
    fire.Fire(build)
